package com.henry.db.migrate.util;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class XmlUtil {
	/**
	 * 传入一个文件路径，读成Document
	 * @param filepath
	 * @return
	 * @throws DocumentException
	 */
	public static Document loadXml(String filepath) throws DocumentException{
		SAXReader reader = new SAXReader();
		Document document = reader.read(CommonUtil.getRelativePath(filepath));
		return document;
	}
	
	public static void uploadXml(Document document,String filepath) throws IOException{
		XMLWriter writer = new XMLWriter(new FileWriter(CommonUtil.getRelativePath(filepath)));
		writer.write(document);
		writer.close();
	}
	
	public static String getXmlNode(String xmlstr, String path)
			throws DocumentException {
		return getXmlNodeValue(DocumentHelper.parseText(xmlstr), path);
	}

	/**
	 * 获取xml文档指定节点的值
	 * @param doc
	 * @param path
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static String getXmlNodeValue(Document doc, String path) {
		String[] paths = path.split("@");
		String[] layers = paths[0].split("\\.");
		Element rootElement = doc.getRootElement();
		Element curElement = rootElement;
		if (layers[0].equals(rootElement.getName())) {
			for (int i = 1; i < layers.length; i++) {
				int startIndex = layers[i].indexOf('(');
				if (-1 != startIndex) {
					int endIndex = layers[i].indexOf(')');
					int num = Integer.parseInt(layers[i].substring(
							startIndex + 1, endIndex));
					layers[i] = layers[i].substring(0, startIndex);
					List<Element> subElements = curElement.elements(layers[i]);
					Element subElement = subElements.get(num);
					curElement = subElement;
				} else {
					Element subElement = curElement.element(layers[i]);
					if (subElement == null) {
						return null;
					}
					curElement = subElement;
				}
			}
			if (paths.length > 1)
				return curElement.attributeValue(paths[paths.length - 1]);
			return curElement.getText();
		}
		return null;
	}

}
